#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *

import sys; sys.path.insert(0, "..")
import pygl2d
import os

COS60 = 0.866025404
SIN30 = 0.5
IMGPATH = "./data/img/"
HEXIMGPATH= IMGPATH + "hexstiles/"
MASKIMGPATH = IMGPATH + "hexmasks/"

# Tiles status 
ISSELECTED = 1
WITHFOG = 2
ISHIGHLIGHTED = 3
SHOWPASSABLE = 4
OUTOFBOARD = 5

from mischelpers import *

class HexTile(object):
    side = 35
    vstep = 2*COS60*side
    hstep = side*(1+SIN30)
    
    def __init__(self,filename,side,scaling = 1.0):
        self.side = side 
        self.vstep = 2*COS60*self.side 
        self.hstep = self.side*(1+SIN30) 
        self.scaling = scaling
        if filename != None:
            self.image = pygl2d.image.Image(filename)
   #     self.highlightMask = pygl2d.image.Image(filename)
            self.image.scale(scaling)
        else :
            self.image = None
        self.points = [[side*SIN30,0],
                       [side*(SIN30+1),0],
                       [side*2,side*COS60],
                       [side*(SIN30+1),2*side*COS60],
                       [side*SIN30,2*side*COS60],
                       [0,side*COS60],
                       [side*SIN30,0]]
        self.points.reverse()

    """
    pos :
      0
    1   5
    2   4
      3
    """
    
    
    def draw(self,x,y,xhexoff=0,yhexoff=0,xpixoffset=0,ypixoffset=0,pos = 0): # upper left coordinate
        if self.image==None:
            return
        if (x % 2) == 0:
            offset = 0
        else :
            offset = 0.5
        
        xp = (x+xhexoff)*self.hstep + xpixoffset
        yp = (y+yhexoff+offset)*self.vstep + ypixoffset
        self.image.rotate(pos*60) 
        self.image.draw([xp,yp])

    def drawOnSurface(self,surf,x,y,xhexoff=0,yhexoff=0,xpixoffset=0,ypixoffset=0,pos = 0,scale=1):
        if self.image==None:
            return
        # Here we do not want to use pygl2d since it's blitting.
        # So we use the pygame functions
        # However, keep in mind that this function should be used only in some kinds of initialization.
        if (x % 2) == 0:
            offset = 0
        else :
            offset = 0.5
        
        xp = (x+xhexoff)*self.hstep*scale + xpixoffset
        yp = (y+yhexoff+offset)*self.vstep*scale + ypixoffset

        #img = pygame.transform.rotozoom(self.image.image,0,scale)
        #rect = img.get_rect()
        #img = pygame.transform.rotozoom(self.image.image,pos*60,scale)
        img = pygame.transform.rotozoom(self.image.image,0,scale)
        #if pos!= 0 and pos!=3:
        #    x1,y1 = img.get_rect().bottomright
        #    x0 = x1 - rect.width
        #    y0 = y1 - rect.height
        #    rect.move_ip(x0,y0)
        
        surf.blit(img,(xp,yp))

    
class HexMaskTile(HexTile):
    def __init__(self,filename,side,scaling = 1.0):
        HexTile.__init__(self,filename,side,scaling)
        if self.image!=None:
            self.image.colorize(255,255,255,100)
        

class HexBoardTile(HexTile):
    def __init__(self,filename,side,scaling = 1.0):
        HexTile.__init__(self,filename,side,scaling )
        self.highlight = mapHexTileMasks.getTile("highlight")
        self.fog = mapHexTileMasks.getTile("fog")
        self.outofboard = mapHexTileMasks.getTile("outofboard")

    def drawHighlight(self,xp,yp):
        self.highlight.image.draw([xp,yp])
        
    def drawFog(self,points):
        pygl2d.draw.polygon(points[:-1],[0,0,0],alpha=100,aa=True)

    def drawOutOfBoard(self,xp,yp):
        self.outofboard.image.draw([xp,yp])

    def drawSelected(self,points):
        pygl2d.draw.lines(points,[255,0,0],alpha=255.0,width=4,aa=True)

    def drawPos(self,points,pos):
        if pos == 0:
            pos = 6
        i1 = pos - 1
        i2 = pos + 1
        pygl2d.draw.lines(points[i1:i2],[0,255,0],alpha=255.0,width=4,aa=True)
        

    def drawText(self,points,text):
        xm=0
        ym=0
        N = len(points)
        for x,y in points:
            xm += x
            ym += y
        xm = xm / N - 5
        ym = ym / N 
        rtext = getRenderText(text)
        rtext.draw([xm, ym])


    def drawInfos(self,x,y,xhexoff=0,yhexoff=0,xpixoffset=0,ypixoffset=0,pos = 0,FLAGS = None,passables = [],text=""):
        
        vstep = self.vstep 
        hstep = self.hstep 
        if (x % 2) == 0:
            offset = 0
        else :
            offset = 0.5
        xp = (x+xhexoff)*hstep + xpixoffset
        yp = (y+yhexoff+offset)*vstep + ypixoffset
        
        points=[]
        for x1,y1 in self.points:
            points.append([x1+xp,y1+yp])

        if FLAGS != None:
            for flag in FLAGS:
                
                if flag == ISHIGHLIGHTED:
                    self.drawHighlight(xp,yp)
                elif flag == ISSELECTED:
                    self.drawSelected(points)
                elif flag == OUTOFBOARD:
                    self.drawOutOfBoard(xp,yp)
                #elif flag == WITHFOG :
                #    self.drawFog(points)
        if len(text)>0:
            self.drawText(points,text)

# HexTile types 
MASK = 1
BOARD = 2

HexType2Const = {MASK : HexMaskTile, BOARD : HexBoardTile}

class TileCollection(object):
    def __init__(self,path = HEXIMGPATH, side = 35,scaling=1.0,hextype = BOARD):
        self.tiles = {}
        self.hextype = hextype
        self.HexTypeConst = HexType2Const[self.hextype]
        self.side = side
        self.path = path
        self.setTileScaling(scaling)
        
        

    def setTileScaling(self,scaling):
        self.newSide = self.side * scaling # Side for hexagonal tiles
        self.scaling = scaling
        self.load()
        self.height = 2*COS60*self.newSide # Height and width of the tiles in this collection
        self.width= self.newSide*(1+SIN30)
    
    def load(self):
        path = self.path
        imgs = os.listdir(path)
        for filename in imgs:
            if filename.endswith(".png"):
                tilename = filename.split(".")[0]
                self.tiles[tilename]=self.HexTypeConst(path+filename,self.newSide,self.scaling)
        self.tiles[None]=self.HexTypeConst(None,self.newSide,self.scaling) # empty tile

    def getTile(self,tilename):
        return self.tiles[tilename]



mapHexTileMasks = TileCollection(MASKIMGPATH,35,1,MASK)
mapTiles = TileCollection(HEXIMGPATH,35,1,BOARD)

minimapTiles = TileCollection(HEXIMGPATH,35,0.2,BOARD)

if __name__=="__main__":
    #init pygl2d
    
    tile = mapTiles.tiles["basicwall"]
    vstep = mapTiles.height
    hstep = mapTiles.width
    tileBunch = [(0,1,1),(1,0,0),(2,1,5),
                 (0,2,2),(1,2,3),(2,2,4)]
    
    #create starting objects
    clock = pygame.time.Clock()
    running = 1
    
    while running:
        clock.tick(60.0)
        theta = 0
       
        for e in pygame.event.get():
            if e.type == QUIT:
                running = 0
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    running = 0
        pygl2d.window.begin_draw()  
       
        for x,y,pos in tileBunch:
            
            if (x % 2) == 0:
                offset = 0
            else :
                offset = 0.5
            xp = x*hstep
            yp = (y+offset)*vstep

            
            tile.draw(xp,yp,pos)
            theta +=1
            
            
        pygl2d.window.end_draw()
        pygame.display.flip()

    pygame.quit()
